package com.yuzhihao.writejvm.attributes.runtimevta;

import com.yuzhihao.writejvm.attributes.Attributes;
import com.yuzhihao.writejvm.clazz.ClassInfo;
import com.yuzhihao.writejvm.read.Parse;
import com.yuzhihao.writejvm.read.ReadClassFileFatory;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.log4j.Log4j2;

import java.io.DataInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * RuntimeVisibleTypeAnnotationsAttribute  和 RuntimeInvisibleTypeAnnotationsAttribute 结构是异一样的
 * <a href="https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.7.20">RuntimeVisibleTypeAnnotationsAttribute</a>
 *
 * @author yzh
 * @since 2021年12月11日16:00:11
 */
@Data
@Log4j2
@EqualsAndHashCode(callSuper = true)
public class RuntimeVisibleTypeAnnotationsAttribute extends Attributes {

    protected int num_annotations_u2 = 2;

    protected int num_annotations;

    protected List<TypeAnnotation> tas = new ArrayList<>();

    public RuntimeVisibleTypeAnnotationsAttribute(String name){
        super();
        super.setAttribute_name(name);
    }

    @Override
    public void parse(DataInputStream dis, ClassInfo ci) {
        try {
            super.attribute_length = Parse.byteToInt(super.attribute_length_u4, dis);
            this.num_annotations = Parse.byteToInt(this.num_annotations_u2, dis);

            int i = 0;
            while (i < this.num_annotations){
                int item = Parse.byteToInt(TypeAnnotation.target_type_u1,dis);
                TypeAnnotation ta = ReadClassFileFatory.tt_instance(item);
                ta.parse(dis,ci);
                this.tas.add(ta);
                i++;
            }
        } catch (IOException e) {
            log.error(e);
        }
    }

}
